import React, { PureComponent } from 'react';
import { TreeSelect, Tooltip } from 'antd';

class TreeSelectItemC extends PureComponent {
  state = {
    value: undefined,
    showTooltip: true, //下拉框展开时隐藏tooltip
    tooltipInfo: '', // 鼠标移动到组件，展示当前选中项全称
  };

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.onRef(this);
    if (this.props.initialValue != undefined && this.props.initialValue != null) {
      this.onChangeInit(this.props.initialValue);
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.value) {
      const ds = this.props.dataSource && this.props.dataSource.length > 0 ? JSON.stringify(this.props.dataSource) : '';
      const dsN = nextProps.dataSource && nextProps.dataSource.length > 0 ? JSON.stringify(nextProps.dataSource) : '';
      const init = nextProps.isMultiple ? (this.props.value && this.props.value.length > 0 ? JSON.stringify(this.props.value) : '') : this.props.value;
      const initN = nextProps.isMultiple ? (nextProps.value && nextProps.value.length > 0 ? JSON.stringify(nextProps.value) : '') : nextProps.value;
      if (ds != dsN || init != initN) {
        this.setTooltip(nextProps.value, nextProps);
      }
      this.setState({
        value: nextProps.value,
      });
    } else {
      this.setState({
        value: undefined,
        tooltipInfo: '', // 鼠标移动到组件，展示当前选中项全称
      });
    }
  }

  findtitle = (value, element) => {
    let arr = [];
    if (value && value.length) {
      let data = value.filter((children) => children.value == element);
      if (data && data.length) {
        arr = [...data];
      } else {
        value.map((item) => {
          arr = this.findtitle(item.children, element).length ? this.findtitle(item.children, element) : arr;
        });
      }
    }
    return arr;
  };

  // 设置tooltip
  setTooltip = (e, propT = this.props) => {
    let { dataSource, isMultiple } = propT;
    let tooltipInfo = '';
    if (e != undefined && e != null) {
      if (Array.isArray(e) && isMultiple) {
        // 多选
        e.forEach((element, index) => {
          let find = [];
          dataSource.map((item, i) => {
            if (item.value == element) {
              find.push(item);
            } else {
              let arr = this.findtitle(item.children, element);
              if (arr && arr.length > 0) {
                find.push(...arr);
              }
            }
          });

          if (find && find.length > 0) {
            tooltipInfo += find[0].title;
          }
          // 最后一个元素之后不用换行
          if (index != e.length - 1) {
            tooltipInfo += '\r\n';
          }
        });
      } else {
        // 单选
        let find = [];
        dataSource.map((item, i) => {
          if (item.value == e) {
            find.push(item);
          } else {
            if (dataSource[i].children && dataSource[i].children.length > 0) {
              let data = dataSource[i].children.filter((children) => children.value == e);
              find.push(...data);
            }
          }
        });
        if (find && find.length > 0) {
          tooltipInfo += find[0].title;
        }
      }
    }

    this.setState({
      tooltipInfo: tooltipInfo == '' ? '' : <div style={{ whiteSpace: 'pre' }}>{tooltipInfo}</div>,
    });
  };

  onChangeInit = (e, option) => {
    this.setState({
      value: e,
    });
    this.setTooltip(e);
  };

  // 响应下拉变更事件
  onChange = (e, option) => {
    this.setState({
      value: e,
    });
    this.props.onChange(e, option);
    this.setTooltip(e);
  };

  onDropdownVisibleChange = (open) => {
    this.setState({
      showTooltip: !open,
    });
    this.props.onDropdownVisibleChange(open, this.props.form.getFieldValue(this.props.dataIndex));
  };

  render() {
    const {
      onTreeExpand,
      treeExpandedKeys,
      styleRow,
      initialValue,
      placeholder,
      onSelect,
      onDeselect,
      disabled,
      dataSource,
      isMultiple,
      treeCheckable,
      allowClear,
      treeDefaultExpandAll,
      showSearch,
      showCheckedStrategy,
      maxTagCount,
      filterTreeNode,
      onSearch,
      dropdownClassName,
      treeCheckStrictly,
      positionBody,
    } = this.props;
    return (
      <Tooltip title={this.state.showTooltip ? this.state.tooltipInfo : ''}>
        <div>
          <TreeSelect
            {...this.props}
            getPopupContainer={(triggerNode) => (!positionBody ? triggerNode.parentNode : document.body)}
            value={this.state.value}
            treeCheckStrictly={treeCheckStrictly}
            dropdownClassName={dropdownClassName} //下拉菜单的 className 属性
            onSearch={onSearch}
            filterTreeNode={filterTreeNode}
            maxTagCount={maxTagCount}
            placeholder={placeholder} // 占位符
            onChange={this.onChange} // 选中树节点时调用此函数
            onSelect={onSelect} // 选择值时触发此函数
            onDeselect={onDeselect} // 取消选择时触发此函数
            onDropdownVisibleChange={this.onDropdownVisibleChange} //下拉框展开或关闭时触发此函数
            treeData={dataSource} // 数据源
            multiple={isMultiple} // 支持多选（当设置 treeCheckable 时自动变为 true）
            treeCheckable={treeCheckable} // 显示 checkbox
            allowClear={allowClear} // 显示清除按钮
            treeDefaultExpandAll={treeDefaultExpandAll} // 默认展开所有树节点
            showSearch={isMultiple ? true : showSearch} // 是否支持搜索框
            showCheckedStrategy={showCheckedStrategy} // 定义选中项回填的方式.TreeSelect.SHOW_ALL: 显示所有选中节点(包括父节点). TreeSelect.SHOW_PARENT: 只显示父节点(当父节点下所有子节点都选中时). 默认只显示子节点.
            searchPlaceholder='请输入查询条件' // 搜索框默认文字
            treeNodeFilterProp='title' // 输入项过滤对应的 treeNode 属性
            treeDefaultExpandedKeys={[initialValue]} // 默认展开的树节点
            disabled={disabled}
            style={styleRow ? styleRow : { width: '100%' }}
            defaultValue={initialValue}
            treeExpandedKeys={treeExpandedKeys}
            onTreeExpand={onTreeExpand}
          />
        </div>
      </Tooltip>
    );
  }
}

export default TreeSelectItemC;
